#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Zhangcl
from core import main
from conf import setting
import os
import configparser
import paramiko
import threading
class File_operate(object):
    def __init__(self):
        pass
    def menu(self):
        choise_menu = '''
                \033[1;31m
                ---------Use Cmd----------
                1. 选择主机传输文件
                2. 选择主机组批量传输文件
                3. 返回上一级目录
                4. 退出
                \033[0m
                '''
        menu_dict = {
            '1':File_operate.file_host,
            '2':File_operate.file_host_group,
            '3':File_operate.go_back,
            '4':'exit'
        }
        while True:
            print(choise_menu)
            choise = input('请选择>>>')
            if choise in menu_dict:
                if choise == '4':
                    exit()
                else:
                    menu_dict[choise](self)
            else:
                print('输入错误！')

    def file_host_group(self):
        host_path = setting.HOST_FILE_PATH
        group_list = os.listdir(host_path)
        for index, item in enumerate(group_list):
            print(index, item)
        group_choise = input('请选择主机组>>>')
        if group_choise.isdigit():
            if group_list[int(group_choise)]:
                save_path = os.path.join(setting.HOST_FILE_PATH, group_list[int(group_choise)])
                config = configparser.ConfigParser()
                config.read(save_path)
                host_list = config.sections()#获取主机组中所有主机
                t_obj = []#创建一个空列表用来存放线程
                cmd_obj = File_operate()
                cmd = input('>>>').strip()
                cmd_list = cmd.split()
                for i in host_list:
                    host_info = {}#
                    host_info['hostname'] = config.get(i, 'hostname')
                    host_info['port'] = config.getint(i, 'port')
                    host_info['user'] = config.get(i, 'user')
                    host_info['passwd'] = config.get(i, 'passwd')
                    t = threading.Thread(target=cmd_obj.send_file, args=(host_info, cmd_list))#创建一个线程执行paramiko模块
                    t.start() #启动线程
                    t_obj.append(t)#为了不阻塞后面的线程启动，添加进之前的空列表
                for f in t_obj:#循环线程实例列表，等待所有线程执行完毕
                    f.join()#等待线程执行完毕

    def file_host(self):
        host_path = setting.HOST_FILE_PATH
        group_list = os.listdir(host_path)
        for index, item in enumerate(group_list):
            print(index, item)
        group_choise = input('请选择主机组>>>')
        if group_choise.isdigit():
            if group_list[int(group_choise)]:
                save_path = os.path.join(setting.HOST_FILE_PATH, group_list[int(group_choise)])
                config = configparser.ConfigParser()
                config.read(save_path) #读取选取的主机组
                host_list = config.sections()
                for index, item in enumerate(host_list):
                    print(index, item)
                host_choise = input('请选择需要操作的主机>>>')
                if host_choise.isdigit():
                    if host_list[int(host_choise)]:
                        host_info = {}#将需求的主机放入列表
                        use_host = host_list[int(host_choise)]
                        host_info['hostname'] = config.get(use_host, 'hostname')
                        host_info['port'] = config.getint(use_host, 'port')
                        host_info['user'] = config.get(use_host, 'user')
                        host_info['passwd'] = config.get(use_host, 'passwd')
                        print(host_info)
                        file_cmd = input('>>>').strip()
                        cmd_list = file_cmd.split()
                        file_obj = File_operate()
                        file_obj.send_file(host_info,cmd_list) #将主机信息和需要执行的操作传给paramiko模块进行操作


    def send_file(self,host_info,cmd_list):

        try:

            transport = paramiko.Transport((host_info['hostname'], host_info['port'])) #绑定ip和端口
            transport.connect(username=host_info['user'], password=host_info['passwd']) #进行连接
            sftp = paramiko.SFTPClient.from_transport(transport)

            if len(cmd_list) == 3:
                action = cmd_list[0] #判断用户动作
                if action == 'put':
                    location_file = cmd_list[1]
                    host_file = cmd_list[2]
                    if os.path.isfile(location_file):
                        # 将location.py 上传至服务器 /tmp/test.py
                        sftp.put(location_file, host_file)
                        print('\n==================%s================' %host_info['hostname'])
                        print('上传文件成功！')
                    else:
                        print('本地文件不存在！')
                elif action == 'get':
                    host_file = cmd_list[1]
                    location_file = cmd_list[2]
                    path, ex = os.path.splitext(location_file)[0], os.path.splitext(location_file)[1]
                    #获取需要下载到本地文件的文件名和扩展名
                    location_file_host = path+'_'+host_info['hostname']+ex
                    #将文件名重命名为对应服务器hostname的文件
                    if os.path.isfile(location_file_host) is not True:
                        # 将remove_path 下载到本地 local_path
                        sftp.get(host_file, location_file_host)
                        print('\n================%s================' %host_info['hostname'])
                        print('下载文件成功！')
                    else:
                        print('本地文件已存在！')
                else:
                    print('输入错误！')
            else:
                print('输入错误！')

        except TimeoutError as e:
            print(e)

    def go_back(self):
        back_obj = main.Manage()
        back_obj.user_choise()

